//
//  SpotInfoProductView.swift
//  swiftProject
//
//  Created by ZhangSai on 2021/7/5.
//

import UIKit
import HandyJSON

class SpotInfoProductView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    var productStr:String = ""
    var selectConditionModel:ConditionModel!
    typealias SpotInfoProductBlock = () -> Void
    var spotInfoProductBlock : SpotInfoProductBlock!
    var titles:Array<String>!
    var dataArray = Array<Array<ConditionModel>>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.white
        titles = [ZslanguageTool.sharedLanguageTool().getIanguageWithKey(key: LanguageHeader.WL_spot_goodsType)]
        var goodSName = CacheTool.cacheTool.getGoodsType()
        if goodSName.count <= 0 {
            Constants.window?.makeToastActivity(.center)
            HttpService.sharedHttpService().getGoodsTypeSuccess { (state) in
                Constants.window?.hideToastActivity()
                if state {
                    goodSName = CacheTool.cacheTool.getGoodsType()
                    self.setUI(goodSName: goodSName)
                }
            }
        } else {
            self.setUI(goodSName: goodSName)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(goodSName:Array<String>) {
        var orderData = Array<Array<Dictionary<String, Any>>>()
        var ary = Array<Dictionary<String, Any>>()
        for name in goodSName {
            let dic:Dictionary = ["condition":name,"isSelect":false] as [String : Any]
            ary.append(dic)
        }
        orderData.append(ary)
        for list in orderData {
            var section = Array<ConditionModel>()
            for item in list {
                let condition:ConditionModel = ConditionModel.deserialize(from: item)!
                if condition.condition == productStr {
                    condition.isSelect = true
                    selectConditionModel = condition
                }
                section.append(condition)
            }
            dataArray.append(section)
        }
        self.addSubview(self.view)
        self.view.snp.makeConstraints { (make) in
            make.top.equalTo(self.snp.top).offset(0);
            make.right.equalTo(self.snp.right).offset(0);
            make.left.equalTo(self.snp.left).offset(0);
            make.height.equalTo(2.5);
        }
        self.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.top.equalTo(self.snp.top).offset(2.5);
            make.bottom.equalTo(self.snp.bottom).offset(-0);
            make.right.equalTo(self.snp.right).offset(15);
            make.left.equalTo(self.snp.left).offset(15);
        }
        collectionView.reloadData()
    }
    
    func setProductStr(productStr:String)  {
        self.productStr = productStr
        for ary in dataArray {
            for condition in ary {
                if condition.condition == productStr {
                    condition.isSelect = true
                    selectConditionModel = condition
                    break
                }
            }
        }
        self.collectionView.reloadData()
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:SpotProductCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SpotProductCollectionCell
        let item:ConditionModel = dataArray[indexPath.section][indexPath.row]
        cell.conditionLab.text = item.condition
        if item.isSelect {
            cell.conditionLab.backgroundColor = UIColor.init(hexString: "#FFD10A")
            cell.conditionLab.layer.borderColor = UIColor.clear.cgColor
        } else {
            cell.conditionLab.backgroundColor = UIColor.clear
            cell.conditionLab.layer.borderColor = UIColor.init(hexString: "#7E7E7E").cgColor
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: frame.size.width, height: 40)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader  {
            let headerView:OrderConditionReusableView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "cell2", for: indexPath) as! OrderConditionReusableView
            headerView.setGroupTitle(groupTitle: titles[indexPath.section])
            return headerView
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let condition:ConditionModel = dataArray[indexPath.section][indexPath.row]
        condition.isSelect = !condition.isSelect
        if condition.isSelect {
            selectConditionModel.isSelect = false
            selectConditionModel = condition
        } else {
            selectConditionModel = nil
        }
        collectionView.reloadData()
        if (spotInfoProductBlock != nil) {
            spotInfoProductBlock()
        }
    }
    lazy var collectionView: UICollectionView = {
        let layout:UICollectionViewLeftAlignedLayout = UICollectionViewLeftAlignedLayout.init()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 15
        let itmeW:CGFloat = (self.frame.size.width - 60) / 3.0
        layout.itemSize = CGSize.init(width: itmeW, height: 40)
        let collectionView = UICollectionView.init(frame: self.frame, collectionViewLayout:layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.allowsMultipleSelection = true
        collectionView.isScrollEnabled = false
        collectionView.register(UINib.init(nibName: "SpotProductCollectionCell", bundle: nil), forCellWithReuseIdentifier: "cell")
        collectionView.register(OrderConditionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "cell2")
        return collectionView
    }()
    lazy var view: UIView = {
        let view = UIView.init()
        view.backgroundColor = UIColor.init(hexString: "#EAEAEA")
        return view
    }()
}
